import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeIPListModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../constant/color_constant.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';

import '../../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../../ecycommon/utils/EcyLogger.dart';
import '../../../../ecycommon/utils/EcyRandomUtil.dart';
import '../../../../model/EcyApiCommonResponse.dart';
import '../../model/EcyGoodsHomeIPModel.dart';
import 'Debouncer.dart';

class EcyGoodsIPSelectPage extends EcyCommonBaseWidget {
  // final T listModel;
  // final ValueChanged<List<dynamic>> onSelected;
  // EcyGoodsIPAndCategorySelectPage(this.listModel, this.onSelected);
  @override
  _EcyGoodsIPSelectPageState createState() {
    return _EcyGoodsIPSelectPageState(this);
  }
}

class _EcyGoodsIPSelectPageState extends EcyCommonBaseWidgetState {
  final ScrollController _scrollController = ScrollController();
  bool requesting = false;
  int _total = 0;
  int _page = 1;
  late EcyGoodsHomeIPListModel _myListModel =
      EcyGoodsHomeIPListModel(0, 0, 0, [], false, 0);
  late EcyGoodsHomeIPListModel _allListModel =
      EcyGoodsHomeIPListModel(0, 0, 0, [], false, 0);

  final TextEditingController _searchController = TextEditingController();
  final Debounce debounce = Debounce();

  final EcyCommonBaseWidget controller;

  _EcyGoodsIPSelectPageState(this.controller);

  void _onScroll() {
    if (_page < _total) {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _refreshData(page: ++_page); // 加载更多数据的函数
      }
    }
  }

  Future<bool> _refreshData({int page = 2, String searchVale = ""}) async {
    try {
      Map<String, dynamic> response = await EcyRequestbasemanager()
          .post("/app/commodityIp/list", {"size": "48", "current": page, "name": searchVale});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyGoodsHomeIPListModel allListModel =
            EcyGoodsHomeIPListModel.fromJson(response["data"]);
        _total = allListModel.pages;
        _page = allListModel.current;
        if(page == 1) {
          _allListModel.records.clear();
        }
        if (allListModel.records.isNotEmpty) {
          setState(() {
            _allListModel.records.addAll(allListModel.records);
            refreshSelected(_myListModel, _allListModel);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取IP失败");
    }
    return true;
  }

  @override
  void requestData() async {
    super.requestData();
    try {
      var response = await Future.wait([
        EcyRequestbasemanager().post(
            "/app/userIp/list", {"size": "20", "current": "1", "name": ""}),
        EcyRequestbasemanager().post("/app/commodityIp/list",
            {"size": "48", "current": "1", "name": ""}),
      ]);
      if (response != null) {
        var myIpResp = response[0];
        var allIpResp = response[1];
        if (allIpResp != null && myIpResp != null) {
          var myIPCommonResponse =
              EcyApiCommonResponse.fromJson(myIpResp, (myIpResp) => json);
          var allIpCommonResponse =
              EcyApiCommonResponse.fromJson(allIpResp, (myIpResp) => json);
          if (myIPCommonResponse.code == 0 ||
              myIPCommonResponse.code == 200 &&
                  (allIpCommonResponse.code == 0 ||
                      allIpCommonResponse.code == 200)) {
            reloadIPArea(myIpResp, allIpResp);
          } else {
            EasyLoading.showToast("请稍后再试",
                duration: const Duration(seconds: 2));
          }
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  void reloadIPArea(
      Map<String, dynamic> myIpResp, Map<String, dynamic> allIpResp) {
    EcyGoodsHomeIPListModel myListModel =
        EcyGoodsHomeIPListModel.fromJson(myIpResp["data"]);
    EcyGoodsHomeIPListModel allListModel =
        EcyGoodsHomeIPListModel.fromJson(allIpResp["data"]);
    myListModel.myIp = true;

    _total = allListModel.pages;
    _page = allListModel.current;

    refreshSelected(myListModel, allListModel);

    setState(() {
      _myListModel = myListModel;
      _allListModel = allListModel;
    });
  }

  refreshSelected(EcyGoodsHomeIPListModel myListModel,
      EcyGoodsHomeIPListModel allListModel) {
    for (int i = 0; i < myListModel.records.length; i++) {
      EcyGoodsHomeIPModel item1 = myListModel.records[i];
      for (int j = 0; j < allListModel.records.length; j++) {
        EcyGoodsHomeIPModel item2 = allListModel.records[j];
        if (item1.code == item2.code) {
          item1.selected = true;
          item2.selected = true;
          break;
        }
      }
    }
  }

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(_onScroll);

    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorConstant.White,
      appBar: AppBar(
        backgroundColor: ColorConstant.White,
        centerTitle: true,
        title: Text(
          "全部IP",
          style: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xD9000000),
              fontWeight: FontWeight.w700),
        ),
      ),
      body: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Container(
            color: ColorConstant.White,
            child: Padding(
                padding: EdgeInsets.only(left: 16.w, right: 16.w),
                child: CustomScrollView(
                    controller: _scrollController,
                    slivers: <Widget>[
                      SliverToBoxAdapter(
                        child: getFirstHeader(), // 间距
                      ),
                      getGridView(_myListModel),
                      SliverToBoxAdapter(
                        child: getSecondHeader(), // 间距
                      ),
                      getGridView(_allListModel),
                    ])),
          )),
    );
  }

  SliverGrid getGridView(EcyGoodsHomeIPListModel listModel) {
    return SliverGrid(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, crossAxisSpacing: 16.w, childAspectRatio: 0.8),
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          EcyGoodsHomeIPModel item = listModel.records[index];
          return Container(
              child: listModel.myIp ?? false
                  ? _buildItemWidget(context, index, listModel)
                  : _buildItemWidget2(context, index, listModel));
        },
        childCount: listModel.records.length,
      ),
    );
  }

  Widget _buildItemWidget(
      BuildContext context, int index, EcyGoodsHomeIPListModel listModel) {
    EcyGoodsHomeIPModel item = listModel.records[index];
    return LongPressDraggable(
      data: index,
      onDragStarted: () {
        //开始拖动，备份数据源
        print('item $index ---------------------------onDragStarted');
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        print(
            'item $index ---------------------------onDraggableCanceled,velocity = $velocity,offset = $offset');
        //拖动取消，还原数据源
      },
      onDragCompleted: () {
        //拖动完成，刷新状态，重置willAcceptIndex
        print("item $index ---------------------------onDragCompleted");
      },
      //用户拖动item时，那个给用户看起来被拖动的widget，（就是会跟着用户走的那个widget）
      feedback: itemContainer(index, item, listModel),
      //这个是当item被拖动时，item原来位置用来占位的widget，（用户把item拖走后原来的地方该显示啥？就是这个）
      childWhenDragging: Container(
        child: const Center(
          child: Text(""),
        ),
      ), //这里data使用list的索引，方便交换数据
      child: DragTarget<int>(
        //松手时 如果onWillAccept返回true 那么久会调用
        onAcceptWithDetails: (data) {
          final temp = listModel.records[data.data];
          listModel.records.remove(temp);
          listModel.records.insert(index, temp);
          setState(() {
            _myListModel = listModel;
          });
        },
        //绘制widget
        builder: (context, data, rejects) {
          return itemContainer(index, item, listModel);
        },
        //手指拖着一个widget从另一个widget头上滑走时会调用
        onLeave: (data) {
          print('$data is Leaving item $index');
        },
        //接下来松手 是否需要将数据给这个widget？  因为需要在拖动时改变UI，所以在这里直接修改数据源
        onWillAcceptWithDetails: (data) {
          print('$index will accept item $data');
          return true;
        },
      ),
    );
  }

  Widget _buildItemWidget2(
      BuildContext context, int index, EcyGoodsHomeIPListModel listModel) {
    EcyGoodsHomeIPModel item = listModel.records[index];
    return itemContainer(index, item, listModel);
  }

  Widget itemContainer(
      int index, EcyGoodsHomeIPModel item, EcyGoodsHomeIPListModel listModel) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(mainAxisAlignment: MainAxisAlignment.end, children: [
          GestureDetector(
              child: Image(
                  image: AssetImage(listModel.myIp ?? false
                      ? 'assets/images/ic_home_ip_del.png'
                      : (!(item.selected ?? false)
                          ? "assets/images/ic_home_ip_add.png"
                          : "assets/images/ic_home_ip_add_disenable.png")),
                  width: 12.w,
                  height: 12.w),
              onTap: () {
                if (listModel.myIp ?? false) {
                  delOneItem(index);
                } else {
                  addOneItem(index);
                }
              })
        ]),
        Container(
          margin: EdgeInsets.only(top: 8.h),
          child: CachedNetworkImage(
            width: 44.w,
            height: 44.w,
            imageUrl: (item.iconUrl ?? ""),
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(8.r)),
                  image: DecorationImage(
                      image: imageProvider, fit: BoxFit.contain)),
            ),
            // placeholder: (context, url) =>
            //     CircularProgressIndicator(),
            errorWidget: (context, url, error) => const Icon(Icons.error),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          item.name ?? item.remark ?? "",
          style: TextStyle(
              fontWeight: FontWeight.w300,
              fontSize: 12.sp,
              overflow: TextOverflow.ellipsis,
              color: const Color(0xD9000000)),
        ),
      ],
    );
  }

  Widget getFirstHeader() {
    return SizedBox(
      height: 58.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "首页展示",
                style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFF262626),
                    fontWeight: FontWeight.w700),
              ),
              SizedBox(width: 8.w),
              Text(
                "拖动调整顺序",
                style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF8C8C8C),
                    fontWeight: FontWeight.w500),
              ),
            ],
          ),
          GestureDetector(
              child: Container(
                  width: 36.w,
                  height: 20.h,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.w),
                      border: Border.all(
                          color: const Color(0xFFEA4B9B), width: 1.w)),
                  child: Center(
                      child: Text("完成",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w400,
                              fontSize: 10.sp,
                              color: const Color(0xFFEA4B9B))))),
              onTap: () {
                confirmBtnClicked();
              })
        ],
      ),
    );
  }

  Widget getSecondHeader() {
    return SizedBox(
      height: 56.h,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child: Text(
              "添加IP",
              style: TextStyle(
                  fontSize: 16.sp,
                  color: const Color(0xFF262626),
                  fontWeight: FontWeight.w700),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 4.w),
            height: 36.h,
            width: MediaQuery.of(context).size.width - 100.w,
            child: TextField(
              controller: _searchController,
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                hintText: "搜索",
                hintStyle: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w300,
                    color: const Color(0x73000000)),
                prefixIcon: const Icon(
                  Icons.search,
                  color: Color(0x73000000),
                ),
                // 设置前置图标的约束
                prefixIconConstraints: BoxConstraints(
                  //添加内部图标之后，图标和文字会有间距，实现这个方法，不用写任何参数即可解决
                    minWidth: 30.w
                ),
                contentPadding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                isDense: true,
                border: UnderlineInputBorder(
                  borderRadius: BorderRadius.circular(8.r),
                  borderSide: const BorderSide(
                    color: Color(0x73000000), // 修改下划线颜色
                    width: 1, // 修改下划线宽度
                  ),
                ), // 移除默认边框
                focusedBorder: const UnderlineInputBorder(
                  // 获取焦点时的下划线
                  borderSide: BorderSide(
                    color: Color(0x73000000), // 修改下划线颜色
                    width: 1, // 修改下划线宽度
                  ),
                ),
                enabledBorder: const UnderlineInputBorder(
                  // 默认状态下的下划线
                  borderSide: BorderSide(
                    color: Color(0x73000000), // 修改下划线颜色
                    width: 1, // 修改下划线宽度
                  ),
                ),
              ),
              onChanged: (String value) {
                debounce.setDuration(const Duration(milliseconds: 300), () {
                  _refreshData(page: 1, searchVale: value);
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  confirmBtnClicked() async {
    var arr = [];
    for (int i = 0; i < _myListModel.records.length; i++) {
      arr.add(_myListModel.records[i].code);
    }
    try {
      controller.showLoading();
      var response = await EcyRequestbasemanager()
          .post("/app/userIp/batchAdd", {"ipCodeList": arr});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showSuccess("设置成功", duration: const Duration(seconds: 2));
          Navigator.pop(context, true);
        } else {
          EasyLoading.showError(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showError("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      controller.dismissLoading();
    }
  }

  delOneItem(int index) {
    EcyGoodsHomeIPModel item = _myListModel.records[index];
    item.selected = false;
    for (int i = 0; i < _allListModel.records.length; i++) {
      EcyGoodsHomeIPModel item1 = _allListModel.records[i];
      if (item.code == item1.code) {
        item1.selected = false;
        break;
      }
    }
    _myListModel.records.removeAt(index);
    setState(() {
      _myListModel = _myListModel;
      _allListModel = _allListModel;
    });
  }

  addOneItem(int index) {
    int max = 20;
    EcyGoodsHomeIPModel item = _allListModel.records[index];
    if (item.selected ?? false) {
      return;
    }

    if (_myListModel.records.length == max) {
      EasyLoading.showToast("关注数量已达上限", duration: Duration(seconds: 2));
      return;
    }
    item.selected = true;
    for (int i = 0; i < _myListModel.records.length; i++) {
      EcyGoodsHomeIPModel item1 = _allListModel.records[i];
      if (item.code == item1.code) {
        item1.selected = true;
        break;
      }
    }
    _myListModel.records.add(item);
    setState(() {
      _myListModel = _myListModel;
      _allListModel = _allListModel;
    });
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    _scrollController.dispose();
    _searchController.dispose();
  }
}
